const Book = require('../models/bookModel');

// 获取所有图书
exports.getAllBooks = async (req, res) => {
  try {
    const books = await Book.find();
    res.status(200).json(books);
  } catch (error) {
    res.status(500).json({ message: '获取图书列表失败', error: error.message });
  }
};

// 添加新图书
exports.addBook = async (req, res) => {
  try {
    const newBook = new Book(req.body);
    const savedBook = await newBook.save();
    res.status(201).json(savedBook);
  } catch (error) {
    res.status(500).json({ message: '添加图书失败', error: error.message });
  }
};

// 删除图书
exports.deleteBook = async (req, res) => {
  try {
    const { id } = req.params;
    const deletedBook = await Book.findByIdAndDelete(id);
    if (!deletedBook) {
      return res.status(404).json({ message: '图书未找到' });
    }
    res.status(200).json({ message: '图书删除成功' });
  } catch (error) {
    res.status(500).json({ message: '删除图书失败', error: error.message });
  }
};

// 更新图书
exports.updateBook = async (req, res) => {
  try {
    const { id } = req.params;
    const updatedBook = await Book.findByIdAndUpdate(id, req.body, { new: true });
    if (!updatedBook) {
      return res.status(404).json({ message: '图书未找到' });
    }
    res.status(200).json(updatedBook);
  } catch (error) {
    res.status(500).json({ message: '更新图书失败', error: error.message });
  }
};
